package com.monlyu.util;

public class ByteUtil {

	/**
	 * 字符数组转化为 16进制的字符串
	 * 
	 * @param array
	 * @return 把字节数组变为16进制字符串
	 */
	public static String byte2hex(byte[] input) throws Exception {
		StringBuilder sb = new StringBuilder();
		String stmp = "";
		for (byte b : input) {
			stmp = Integer.toHexString(b & 0XFF);
			if (stmp.length() == 1) {
				sb.append("0" + stmp);
			} else {
				sb.append(stmp);
			}
		}
		return sb.toString();
	}

	/**
	 * 十六进制的字符串转化为字节数组
	 * 
	 * @author monlyu
	 * @since 2010-1-22
	 */
	public static byte[] hex2byte(byte[] b) {
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	/**
	 * 把字符串转化为字节数组,不足八位的补足0
	 * 
	 * @author monlyu
	 * @param str
	 *            入字符串
	 * @param bei
	 *            必须多少为
	 * @since 2010-1-23
	 */
	public static byte[] strTo8byte(String str) {
		byte[] oriByte = str.getBytes();// 23
		int left = oriByte.length % 8;// 7
		int pei = oriByte.length / 8;// 2
		if (left == 0) {
			return oriByte;
		}
		byte[] value = new byte[(pei + 1) * 8];
		for (int i = 0; i < value.length; i++) {
			value[i] = (byte) (i < oriByte.length ? oriByte[i] : '0');
		}
		return value;
	}
}
